package cn.lixu.filter;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

/**
 * @author LiXu
 * @date 2022/08/22 0022 11:11:55
 */
@Component
public class LoginCheckFilter extends ZuulFilter {

    //返回前置过滤器
    @Override
    public String filterType() {
        return "pre";
    }

    //执行优先级，数字越小，级别越高，不能为负数
    @Override
    public int filterOrder() {
        return 0;
    }


    //是否执行run方法，false为不执行，TRUE为执行
    @Override
    public boolean shouldFilter() {
        //获取上下文路径
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取请求对象
        HttpServletRequest request = currentContext.getRequest();
        //获取请求的url
        String requestURI = request.getRequestURI();
        //判断请求路径是否以login/register结尾，包含就不执行登录业务校验，所以返回false
        if (StringUtils.endsWithIgnoreCase(requestURI, "login") || StringUtils.endsWithIgnoreCase(requestURI, "register")) {
            return false;
        }
        //如果不包含那么说明用户访问的资源是受保护的资源，那么需要执行登录校验
        return true;
    }


    @Override
    public Object run() throws ZuulException {
        //获取请求对象
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //获取响应对象
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //设置响应对象的返回格式
        response.setContentType("application/json;charset=UTF-8");
        //获取请求头的token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            try {
                // 1.设置响应内容
                HashMap<String, Object> map = new HashMap<>();
                map.put("message", "noLogin");
                map.put("success", false);
                PrintWriter writer = response.getWriter();
                String strJon = JSONObject.toJSONString(map);
                writer.write(strJon);
                //阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        }
        // 如果要放行，这里返回null即可，不用管
        return null;
    }
}
